package com.ice.common;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;


import org.dom4j.Document;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GenerateEntity {
	private static Logger log = LoggerFactory.getLogger(GenerateEntity.class);
	
	public static Object byXml(String xml,String className,Object object){
		long startTime = System.currentTimeMillis();
		try {
			//将xml字符串生产xml文档
			Document document =DocumentHelper.parseText(xml);
			//获取xml文档根节点
			Element rootElement = document.getRootElement();
			//获取xml文档根节点下的子节点
			List<Element> list = rootElement.elements();
			//将list转换成ietrator
			Iterator<Element> iterator= list.iterator();
			
			Class<?> c  = Class.forName(className);
			object  = c.newInstance();
			
			while(iterator.hasNext()){
				Element element  = iterator.next();
				Field field = c.getDeclaredField(element.getName());
				//设置set方法
				Method method  = c.getDeclaredMethod("set"+element.getName(), field.getType());
				//赋值
				method.invoke(object, element.getText());
			}
			log.debug(IceLog.printLog(startTime, "java类放射将xml变成实力", "实体类"+object.toString()));
			return object;
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.debug(IceLog.printLog(startTime, "java类放射将xml变成实力", "实体类失败"));
		}
		log.debug(IceLog.printLog(startTime, "java类放射将xml变成实力", "实体类失败"));
		return null;
	}
}
